
//
//  HistoryViewController.m
//  Runone
//
//  Created by runone01 on 16/8/25.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "CarManagerHistoryViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "Define.h"
#import "MJExtension.h"
#import "AllLastestVehicleDynamic.h"
#import "MovingAnnotationView.h"
#import "TracingPoint.h"
#import "Util.h"
#import "UIView+Addition.h"

@interface CarManagerHistoryViewController ()<MAMapViewDelegate>
@property (nonatomic, strong) MAMapView *map;//地图
@property (nonatomic, strong) MAPointAnnotation * car;

@end

@implementation CarManagerHistoryViewController {
    NSMutableArray * _tracking;
    CFTimeInterval _duration;
    
}

#pragma      - - - - - -- 车辆管理界面历史轨迹 

- (void)initRoute
{
    _duration = 15.0;
    
    NSUInteger count = self.dataSource.count;
    CLLocationCoordinate2D * coords = malloc(count * sizeof(CLLocationCoordinate2D));
    for (int i=0; i<count; i++) {
        
        _CarManagerModel=self.dataSource[i];
        
        coords[i] = CLLocationCoordinate2DMake(_CarManagerModel.Latitude,  _CarManagerModel.Longitude );
    }
    
    [self showRouteForCoords:coords count:count];
    [self initTrackingWithCoords:coords count:count];
    
    if (coords) {
        free(coords);
    }
    
}

//开启定位
- (void)showRouteForCoords:(CLLocationCoordinate2D *)coords count:(NSUInteger)count
{
    //show route
    MAPolyline *route = [MAPolyline polylineWithCoordinates:coords count:count];
    [self.map addOverlay:route];
    
    NSMutableArray * routeAnno = [NSMutableArray array];
    for (int i = 0 ; i < count; i++)
    {
        MAPointAnnotation * a = [[MAPointAnnotation alloc] init];
        a.coordinate = coords[i];
        a.title = @"route";
        [routeAnno addObject:a];
    }
    [self.map addAnnotations:routeAnno];
    [self.map showAnnotations:routeAnno animated:NO];
    
}

- (void)initTrackingWithCoords:(CLLocationCoordinate2D *)coords count:(NSUInteger)count {
    _tracking = [NSMutableArray array];
    for (int i = 0; i<count - 1; i++)
    {
        TracingPoint * tp = [[TracingPoint alloc] init];
        tp.coordinate = coords[i];
        tp.course = [Util calculateCourseFromCoordinate:coords[i] to:coords[i+1]];
        [_tracking addObject:tp];
    }
    
    TracingPoint * tp = [[TracingPoint alloc] init];
    tp.coordinate = coords[count - 1];
    tp.course = ((TracingPoint *)[_tracking lastObject]).course;
    [_tracking addObject:tp];
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    NSLog(@"%lu",(unsigned long)_dataSource.count);
    UILabel *titleLabel            = [[UILabel alloc] init];
    titleLabel.size                = CGSizeMake(100, 30);
    titleLabel.text                = @"历史轨迹";
    titleLabel.textAlignment       = NSTextAlignmentCenter;
    titleLabel.textColor           = [UIColor whiteColor];
    self.navigationItem.titleView  = titleLabel;

    
    [self.view addSubview:self.map];
    for (IntVclDynamicHistoryModel *model in _dataSource) {
//        NSLog(@"%@,%f,%ld",model.VehicleNo,model.Latitude,(long)model.Longitude);
    }
    [self initBtn];
    [self initAnnotation];
}

- (void)mov:(UIButton *)btn
{
    btn.selected=!btn.selected;
    if (btn.selected) {
        [btn setBackgroundImage:[UIImage imageNamed:@"map_stop_track"] forState:UIControlStateNormal];
    }
    else
    {
        [btn setBackgroundImage:[UIImage imageNamed:@"map_play_track"] forState:UIControlStateNormal];
    }
    [self.map removeAnnotation:_car];
    TracingPoint * start = [_tracking firstObject];
    MAPointAnnotation *car = [[MAPointAnnotation alloc] init];
    car.coordinate = start.coordinate;
    car.title = @"Car";
    _car=car;
    [self.map addAnnotation:_car];
    
    MovingAnnotationView * carView = (MovingAnnotationView *)[self.map viewForAnnotation:self.car];
    
    [carView addTrackingAnimationForPoints:_tracking duration:_duration];
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        MovingAnnotationView *annotationView = (MovingAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MovingAnnotationView alloc] initWithAnnotation:annotation
                                                              reuseIdentifier:pointReuseIndetifier];
        }
        
        if ([annotation.title isEqualToString:@"Car"])
        {
            UIImage *imge  =  [UIImage imageNamed:@"map_car_track.png"];
            annotationView.image =  imge;
            CGPoint centerPoint=CGPointZero;
            [annotationView setCenterOffset:centerPoint];
        }
        else if ([annotation.title isEqualToString:@"route"])
        {
            annotationView.image = [UIImage imageNamed:@"trackingPoints.png"];
        }
        
        return annotationView;
    }
    
    return nil;
}


- (MAPolylineRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        
        polylineRenderer.lineWidth   = 3.f;
        polylineRenderer.strokeColor = [UIColor colorWithRed:0 green:0.47 blue:1.0 alpha:0.9];
        
        return polylineRenderer;
    }
    
    return nil;
}

- (void)initAnnotation
{
    [self initRoute];
    
    /* Step 1. */
    //show car
    
    TracingPoint * start = [_tracking firstObject];
    self.car = [[MAPointAnnotation alloc] init];
    self.car.coordinate = start.coordinate;
    self.car.title = @"Car";
    [self.map addAnnotation:self.car];
    
}

- (MAMapView *)map
{
    if (!_map)
    {
        _map = [[MAMapView alloc] initWithFrame:self.view.frame];
        [_map setDelegate:self];
        
        //加入annotation旋转动画后，暂未考虑地图旋转的情况。
        _map.rotateCameraEnabled = NO;
        _map.rotateEnabled = NO;
    }
    return _map;
}


- (void)initBtn {
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(30, self.view.frame.size.height/2+200, 34, 34);
    //btn.backgroundColor = [UIColor greenColor];
    [btn setTitle:@"开始" forState:UIControlStateNormal];
    btn.backgroundColor=[UIColor clearColor];
    btn.tintColor=[UIColor clearColor];
    [btn addTarget:self action:@selector(mov:) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundImage:[UIImage imageNamed:@"map_play_track.png"] forState:UIControlStateNormal];
    
    [self.view addSubview:btn];
}

-(void)defaultAnnimation {
    NSInteger i = _dataSource.count/2;
    _CarManagerModel=_dataSource[i];
    MACoordinateSpan span = MACoordinateSpanMake(0.7, 0.8);
    CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(_CarManagerModel.Latitude,   _CarManagerModel.Longitude);
    MACoordinateRegion region = MACoordinateRegionMake(centerCoordinate, span);
    _map.region = region;
}

-(void)viewDidAppear:(BOOL)animated {
    [self defaultAnnimation];
}



@end

